package com.qf.user.manager.api;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qf.common.bean.R;
import com.qf.common.model.QfUser;
import com.qf.common.utils.JwtUtil;
import com.qf.user.manager.bean.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.UUID;

/**
 * 管理员认证Controller
 * @author 千锋健哥
 */
@RestController
@RequestMapping("/user/auth")
public class UserAuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 管理员登录认证
     * @param qfUser
     * @return
     */
    @PostMapping("/doLogin")
    public R<String> login(@RequestBody QfUser qfUser) {
        if (qfUser == null) {
            R.fail("用户名密码不能为空");
        }
        if (StringUtils.isEmpty(qfUser.getUserName())
                || StringUtils.isEmpty(qfUser.getPassword())) {
            R.fail("用户名密码不能为空");
        }

        //1. 调用UserDetailService实现类中的认证方法, 传入页面输入的用户名, 密码
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(qfUser.getUserName(), qfUser.getPassword()));
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("认证失败!");
        }

        //2. 获取当前登录用户的用户名, 从SpringSecurity中获取, 获取到说明用户登录成功.
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userName = loginUser.getQfUser().getUserName();

        //3. 根据用户名生成jwt
        String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), userName, null);

        //4. 将jwt返回给前端
        return R.ok(jwt);
    }

    /**
     * 注销退出
     * @return
     */
    @RequestMapping("/doLogout")
    public R<Boolean> logout() {
        //获取SpringSecurity全局对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //从全局对象中获取当前登录用户的用户对象
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        //获取里面的属性
        Long userId = loginUser.getQfUser().getId();
        //TODO 清除用户登录权限, 如果用户权限保存到redis中缓存了, 那么清除这个缓存就相当于退出
        return R.ok("退出成功!");

    }

}
